<template>
  <el-row class="chat-container">
    <!-- 左侧用户列表 -->
    <el-col :span="6" class="user-list-column">
      <el-card class="user-list-card" shadow="hover">
        <h3>在线用户</h3>
        <el-table :data="onlineUsers" style="width: 100%;height: 500px;overflow-y: auto;" @row-click="startChat" highlight-current-row>
          <el-table-column label="用户" align="center">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.userImage" size="small" />
              <span class="username">{{ scope.row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
           
              <span :style="{ color: 'green' }">在线</span>
           
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>

    <!-- 右侧聊天区 -->
    <el-col :span="18" class="chat-column">
      <div class="chat-box-card" shadow="hover">
        <div class="chat-header">
          <el-avatar :src="currentUser.userImage" size="large" />
          <span class="chat-username">{{ currentUser.userName }}</span>
        </div>

        <!-- 消息列表区域 -->
        <div class="message-list" ref="messageList">
          <div v-for="(message, index) in messages" :key="index"
            :class="['message-item', message.role=='用户' ? 'user-message' : 'customer-service-message']">
            <el-avatar v-if="message.role=='用户'" :src="currentUser.userImage" size="small" />
            <div class="message-content">
              <p>{{ message.msg }}</p>
              <span class="message-time">{{ message.timestamp }}</span>
            </div>
            <el-avatar v-if="message.role=='客服'" :src="customerServiceAvatar" size="small" style=""/>
          </div>
        </div>

        <!-- 输入框和发送按钮固定在底部 -->
        <div class="chat-input-wrapper">
          <div class="chat-input">
            <el-input v-model="newMessage" placeholder="请输入消息..." @keyup.enter="sendMessage" suffix-icon="el-icon-send"
              @keyup.enter.native="sendMessage" />
          </div>

          <div class="send-button">
            <el-button type="primary" @click="sendMessage">发送</el-button>
            <el-button type="danger" @click="closeChat">下班</el-button>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script>

// import { connectWebsocket, closeWebsocket, sendMsg } from "@/utils/websocket";
import { getUsersByids,getTuser } from "@/api/tuser/tuser";
import {getMessage} from "@/api/tcustomer/tcustomer"

export default {
  data() {
    return {
      // 在线用户数据
      onlineUsers: [
        // { name: '用户1', status: '在线', avatar: 'https://randomuser.me/api/portraits/men/1.jpg' },
        // { name: '用户2', status: '在线', avatar: 'https://randomuser.me/api/portraits/women/2.jpg' },
        // { name: '用户3', status: '离线', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
        // { name: '用户4', status: '离线', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
        // { name: '用户5', status: '离线', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
        // { name: '用户6', status: '离线', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
        // { name: '用户7', status: '离线', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
        // { name: '用户8', status: '离线', avatar: 'https://randomuser.me/api/portraits/men/3.jpg' },
      ],
      // 当前聊天用户
      // currentUser: { name: '用户1', status: '在线',avatar: 'https://randomuser.me/api/portraits/men/1.jpg' },
      currentUser:{},
      // 客服头像
      customerServiceAvatar: 'https://randomuser.me/api/portraits/men/4.jpg',
      // 聊天消息列表
      messages: [
      ],
      // 新消息
      newMessage: '',
      // websocket: null,
      ws:null,
    };
  },
  mounted() {
    this.ws = new WebSocket(`ws://localhost:8080/websocket/${this.$store.state.user.id}/客服`);
    
    // this.ws.send()
    // 接受服务端的信息
    this.ws.onmessage = (event) => {
      console.log('收到服务端的消息：', event.data);
      const message = JSON.parse(event.data);
      
      // var userIds = null;
      if(message.role=="客服已重置"){
        const ids = JSON.parse(message.msg)
        if(ids.length!=0){
          getUsersByids(ids).then(res => {
            this.onlineUsers = res;
            this.currentUser = res[0]
          })
        }
      }else if(message.role=="用户"){
        if(this.currentUser.userId == message.id && this.$store.state.user.id == message.targetId){
          this.messages.push(message);
        // getMessage({customerId:this.$store.state.user.id,userId:this.currentUser.userId}).then(res=>{
        //     this.messages = res;
        //    })
        } 
      }

      if(message.msg==='用户已连接'){
        console.log("用户连接：",message)
        const id = JSON.parse(message.targetId)
        getTuser(id).then(res=>{
          // console.log(res)
          this.onlineUsers.push(res)
        })
      }else if(message.msg=='用户已下线'){
          const id = JSON.parse(message.targetId)
          this.onlineUsers.forEach((item, index) => {
            if (item.userId === id) {
              this.onlineUsers.splice(index, 1);
            }
          });
          console.log(this.onlineUsers)
        }
      // this.message= JSON.parse(event.data);
      // const ids = JSON.parse(this.message.msg)
      // console.log('收到服务端的消息：',);
      // getUsersByids(ids).then(res => {
      //   // this.onlineUsers = res.data;
      //   console.log(res)
      // })
     
      
    };

    // 连接打开时触发
    this.ws.onopen = () => {
      console.log('WebSocket 已连接');
    };


    // 错误处理
    this.ws.onerror = (error) => {
      console.error('WebSocket Error:', error);
    };
  },
  created() {
    // this.initWebSocket();
  },
  beforeDestroy() {
    // 组件销毁时关闭 WebSocket 连接
    // if (this.websocket) {
    //   this.websocketClient.close();
    // }
      if (this.ws) {
        this.closeChat()
      // 如果存在连接，则关闭它
      this.ws.close();
      // 可选：清除 this.ws 引用，以避免重复关闭连接
      this.ws = null;
    }
  },
  methods: {
    // initWebSocket () {
    //   connectWebsocket(`ws://localhost:8080/websocket/${this.$store.state.user.id}/客服`, { w: 'S', }, (res) => {
    //   console.log("onWsMessage接收到服务器的数据: ", res)
    //   },
    //   (err) => {
    //     console.log("断开重连");
    //   })
    // },
    // onOpen(event) {
    //   console.log("WebSocket 已连接", event);
    // },
    // 处理 WebSocket 接收到消息时的事件
    // onMessageReceived(event) {
    //   const message = JSON.parse(event.data);
    //   const timestamp = new Date().toLocaleTimeString().slice(0, 5);
    //   this.messages.push({
    //     content: message.msg,
    //     isUser: message.role === '用户', // 判断是用户发的消息还是客服发的消息
    //     timestamp: timestamp,
    //   });
    //   this.$nextTick(() => {
    //     this.scrollToBottom(); // 滚动到最新消息
    //   });
    // },
    // 处理 WebSocket 关闭连接时的事件
    // onClose(event) {
    //   console.log("WebSocket 已关闭", event);
    // },
    // // 开始与指定用户聊天
    startChat(row) {
      // 清空聊天记录
      this.messages = [];
      this.currentUser = row;
      //  
      getMessage({customerId:this.$store.state.user.id,userId:row.userId}).then(res=>{
        this.messages = res;
      })
    },
    // 发送消息
    // sendMessage() {
    //   if (this.newMessage.trim()) {
    //     const timestamp = new Date().toLocaleTimeString().slice(0, 5); // 获取当前时间（时:分）
    //     // 将当前消息添加到聊天记录，isUser 为 false 表示客服消息
    //     this.messages.push({ content: this.newMessage, isUser: false, timestamp: timestamp });
    //     this.newMessage = ''; // 清空输入框
    //     this.$nextTick(() => {
    //       // 发送消息后自动滚动到消息列表的底部
    //       this.scrollToBottom();
    //     });
    //     // this.simulateUserReply(); // 模拟用户回复
    //   }
    // },
     // 发送消息
     sendMessage() {
      const timestamp = new Date().toLocaleTimeString().slice(0, 5); // 获取当前时间（时:分）
      if(this.currentUser.userId==null){
        this.$message.error("请选择用户后在发送");
        return;
      }
      if (this.newMessage.trim()) {
        const message = {
          msg: this.newMessage,
          id: this.$store.state.user.id,
          role: "客服",
          targetId: this.currentUser.userId,
          timestamp: timestamp
        };
        this.messages.push(message);
        // 发送消息到 WebSocket 服务器
        this.ws.send(JSON.stringify(message));
        this.newMessage = ''; // 清空输入框
      }
    },
    // // 模拟用户回复
    // simulateUserReply() {
    //   setTimeout(() => {
    //     const timestamp = new Date().toLocaleTimeString().slice(0, 5);
    //     this.messages.push({ content: '我正在等待您的帮助。', isUser: true, timestamp });
    //     this.$nextTick(() => {
    //       // 用户回复后自动滚动到消息列表的底部
    //       this.scrollToBottom();
    //     });
    //   }, 1000); // 模拟用户延迟回复
    // },
    closeChat(){
      const message = {
          msg: "下班",
          id: this.$store.state.user.id,
          role: "客服",
          targetId: this.currentUser.userId
        };
        // 发送消息到 WebSocket 服务器
        this.ws.send(JSON.stringify(message));
    },

    // 滚动到消息列表的底部
    scrollToBottom() {
      const messageList = this.$refs.messageList;
      messageList.scrollTop = messageList.scrollHeight;
    }
  },
};
</script>

<style scoped>
.chat-container {
  padding: 20px;
}

.user-list-column {
  padding-right: 20px;
}

.user-list-card {
  padding: 10px;
  background-color: #f7f7f7;
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
}
.user-list-card ::-webkit-scrollbar {
    width: 0;  /* 隐藏滚动条 */
}


.username {
  margin-left: 10px;
  font-weight: bold;
}

.chat-column {
  padding-left: 20px;
  width: 70%;
  /* 设置固定宽度 */
  height: 500px;
  /* 设置固定高度 */
  max-width: 100%;
  /* 确保不会超出容器 */
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.chat-username {
  margin-left: 10px;
  font-size: 18px;
  font-weight: bold;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  /* 使消息列表可滚动 */
  margin-bottom: 20px;
  padding-right: 10px;
  padding-left: 10px;
  padding-bottom: 60px;
  /* 为输入框和发送按钮留出空间 */
}

.message-item {
  display: flex;
  align-items: flex-start;
  margin: 40px 0;
  justify-content: flex-end; /* 用户消息对齐右侧 */
}

.user-message {
  justify-content: flex-start;
}

.message-content {
  max-width: 60%;
  padding: 10px;
  border-radius: 5px;
  background-color: #f0f0f0;
  margin-left: 10px;
  margin-right: 10px;
  position: relative;
  word-wrap: break-word; /* 允许在单词内换行 */
  overflow-wrap: break-word; /* 允许在单词内换行，是word-wrap的新名称 */
}


.user-message .message-content {
  background-color: #d1f7d1;
  align-self: flex-start; /* 客服消息在右侧显示 */
}

.customer-service-message .message-content {
  background-color: #f0f0f0;
  align-self: flex-end; /* 用户消息在左侧显示 */
}

.message-time {
  font-size: 12px;
  color: #999;
  position: absolute;
  bottom: -20px;
  right: 10px;
}

/* 输入框和发送按钮固定在底部 */
.chat-input-wrapper {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ddd;
  background-color: #fff;
  position: absolute;
  bottom: 0;
  width: 100%;
  background-color: #f9f9f9;
}

.chat-input {
  flex: 1;
  margin-right: 10px;
}

.send-button {
  flex-shrink: 0;
}
</style>